import personInfo from '@/views/client-manage/components/person-info.vue'
import employeeInfo from '@/views/client-manage/components/employee-info.vue'
import uploadMedia from '@/components/upload-media.vue'
import {getDivision} from '@/admin/api/division'
import {getDictAndPlease} from "~/utils"
import {getObj,addObj,putObj,getClientLesseeByCardId} from '@/views/client-manage/api/clientlessee'
import {validatePhone,validateEmail,validateIdNo} from '~/utils/validate'
export default {
    components: {
        personInfo,
        uploadMedia,
        employeeInfo
    },
    computed: {
        detailAddress(){
            const { provinceCode, cityCode, countyCode } = this.propForm
            let province = this.provinces.find(item => item.value == provinceCode)
            let city = this.citys.find(item => item.value == cityCode)
            let county = this.countys.find(item => item.value == countyCode)
            return `${province ? province.label : ''} ${city ? city.label : ''} ${county ? county.label : ''}`
        },
        selectProvice: function (){
            return this.provinces.find(p => p.value == this.propForm.provinceCode)
        },
        selectCity: function(){
            return this.citys.find(p => p.value == this.propForm.cityCode)
        },
        selectCounty: function(){
            return this.countys.find(p => p.value == this.propForm.countyCode)
        },
        chArea: function() {
            let p = this.selectProvice? this.selectProvice.label : ''
            let c = this.selectCity? this.selectCity.label : ''
            let y = this.selectCounty ? this.selectCounty.label : ''
            return  p + c + y
        }
    },
    props:{
    },
    data() {
        var validateCertificateNum = (rule, value, callback) => {
            if(!value){
                callback()
            }
            this.validateCertificateNumOnly(value,callback)
        };
        return {
            propForm: {
                clientLesseeId:'',
                clientLesseeName:'',
                clientLesseeType:'',
                certificateType:'',
            },
            originalCertificateNum: '',
            optionVal:'',
            uploadFileList:[],
            modelType:'client-manage',
            rules: {
                clientLesseeName: [
                    { required: true, message: "请输入承租方名称", trigger: "blur" },
                ],
                clientLesseeType: [
                    { required: true, message: "请选择承租方类型", trigger: "blur" },
                ],
                certificateType: [
                    { required: true, message: "请选择证件类型", trigger: "blur" },
                ],
                workUnit: [
                ],
                certificateNum: [
                    { required: true, message: "请输入证件号码", trigger: "blur" },
                    { validator: validateCertificateNum, trigger: "change"},
                ],
                categroyEmployment: [
                ],
                registerFund: [
                ],
                unitNature: [
                ],
                primaryBusiness: [
                ],
                phoneNum: [
                    { required: true, message: "请输入手机号码", trigger: "blur" },
                    {validator:validatePhone,trigger: "change"},
                ],
                email: [
                    { required: true, message: "请输入电子邮件", trigger: "blur" },
                    {validator:validateEmail,trigger: "blur"},
                ],
                legalPerson: [
                ],
                legalIdentityCard: [
                    { validator: validateIdNo, trigger: "change"},
                ],
                telephone: [
                ],
                provinceCode: [
                ],
                cityCode: [
                ],
                countyCode: [
                ],
                address: [
                ],
                introduceUnit: [
                ],
                remarks: [
                    {min: 0, max: 100, message: "长度在0-100个字符串", trigger: "blur"},
                ]
            },
            editPersons: [],
            delPersons: [],
            provinces: [],
            citys: [],
            countys: [],
            isAdd: true,
            busId: '',
            url: '/admin/sys-file/upLodeFileAdd',
            fileSize: 50,
            idEdit:false,
            lesseeOptions:[],
            lesseeOptionsCopy:[],
            certificateOptions:[],
            certificateOptionsCopy:[]
        }
    },
    created(){
        if(this.isAdd){
            this.queryProvince()
            this.initClientLesseeType() 
        }
        //获取传递过来的url参数
        this.propForm.clientLesseeId=this.$route.query.id

        if(this.propForm.clientLesseeId){
            //根据url参数查询一条数据
            this.isEdit=true
            this.url='/admin/sys-file/upLodeFileEdit'
            this.initCitySelector()
        }else {

        }
    },
    mounted() {},
    methods: {
        handleTotalPrices(){
            var regPos = /^\d+(\.\d+)?$/;
            if (!regPos.test(this.propForm.registerFund)){
                this.$message.error('注册资金不能小于0且不能包含特殊字符！')
            }

        },

        // 修改时初始化地址选择器
        async initCitySelector(){
            this.busId = this.propForm.clientLesseeId
            // this.$refs.loadFiles.getFiles(this.busId)
            await getObj(this.propForm.clientLesseeId).then((rep) => {
                this.isAdd = false;
                this.propForm = rep.data.data;
                //将客户类型转化为字符串，结合下拉列表
                this.propForm.clientLesseeType+=''
                this.optionVal=this.propForm.clientLesseeType
                this.originalCertificateNum = this.propForm.certificateNum
                //获取省市县区下拉数据
                this.queryProvince();
                if(this.propForm.provinceCode){
                    this.queryCitys(this.propForm.provinceCode)
                }
                if(this.propForm.cityCode){
                    this.queryCounty(this.propForm.cityCode)
                }

          /*      var index1=this.propForm.address.lastIndexOf("市")
                var index2=this.propForm.address.lastIndexOf("区")
                var index3=this.propForm.address.lastIndexOf("县")
                var max = index1>index2 ? index1 : index2
                max= max>index3 ? max : index3
                this.propForm.addressInfo=this.propForm.address.substring(max+1)*/
                this.initClientLesseeType();
                if(this.propForm.clientLesseeType){
                    this.queryCertificateType()
                }
            })
            this.$refs.loadFiles.getFiles(this.busId)
        },
        //验证证件号唯一
        validateCertificateNumOnly (value,callback){
            let certificateType = this.propForm.certificateType;
            let clientLesseeType = this.propForm.clientLesseeType
            if(certificateType==='01'){
                var reg =new RegExp('(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的身份证号码'))
                    }
                }
            }else if(certificateType==='02'){
                var reg =new RegExp('^[\u4E00-\u9FA5]{1,2}(字第)([0-9a-zA-Z]{4,8})(号?)$')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的军官证号码'))
                    }
                }
            }else if(certificateType==='03'){
                reg = new RegExp('^[HMhm]{1}([0-9]{10}|[0-9]{8})$')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的港澳台证号码'))
                    }
                }
            }else if(certificateType==='04'){
                reg = new RegExp('^([EeKkGgDdSsPpHh]\d{8}$)|(^(([Ee][a-fA-F])|([DdSsPp][Ee])|([Kk][Jj])|([Mm][Aa])|(1[45]))\d{7}$)')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的护照号码'))
                    }
                }
            }else if(certificateType==='05'){
                callback()
            }

            if(!this.originalCertificateNum===this.propForm.certificateNum){
                getClientLesseeByCardId({"clientLesseeType":clientLesseeType,"certificateType":certificateType,"certificateNum":value}).then(resp=>{
                    console.log(resp.data,"getClientLesseeByCardId")
                    let data = resp.data
                    if(data.length!=0){
                        return callback(new Error("校验失败，该证件号码已经存在 ！"));
                    }else {
                        callback()
                    }
                })
            }else {
                callback()
            }

        },
        //监听省市区下拉
        handleSelectChange(value, type){
            const { provinceCode, cityCode, countyCode } = this.propForm
            const province = this.provinces.find(item => item.value == provinceCode)
            const city = this.citys.find(item => item.value == cityCode)
            const county = this.countys.find(item => item.value == countyCode)
            this.propForm.address = `${province ? province.label : ''} ${city ? city.label : ''} ${county ? county.label : ''}`
            const methods = {
                provinces: 'queryCitys',
                citys: 'queryCounty',
            }
            type !== 'countys' && this[methods[type]](value)
        },
        queryProvince(){
            getDivision({"lazy": true, parentId: "000000"}).then(rep => {
                let rep_province = rep.data.data
                this.provinces = rep_province.map(p => {
                    return {"label": p.divisionName, "value": p.divisionCode}
                })
            })
        },
        //获取城市
        queryCitys(val){
            getDivision({"lazy": true, parentId: val}).then(rep => {
                let rep_city = rep.data.data
                this.citys = rep_city.map(p => {
                    return {"label": p.divisionName, "value": p.divisionCode}
                })

            })
        },
        //获取县区
        queryCounty(val){
            getDivision({"lazy": true, parentId: val}).then(rep => {
                let rep_county = rep.data.data
                this.countys = rep_county.map(p => {
                    return {"label": p.divisionName, "value": p.divisionCode}
                })
            })
        },
        //初始化承租方类型
        initClientLesseeType(){
            this.lesseeOptions = getDictAndPlease('lessee_type')
            this.lesseeOptionsCopy = this.lesseeOptions
        },
        //点击承租方类型下拉列表后，查询对应的证件类型
        queryCertificateType(){
            if(this.propForm.clientLesseeType==0){
                this.certificateOptions = getDictAndPlease('personage_certificate_type')
                this.certificateOptionsCopy = this.certificateOptions
            }else {
                this.certificateOptions = getDictAndPlease('commercial_certificate_type')
                this.certificateOptionsCopy = this.certificateOptions
            }
        },
        commit(){
            this.$refs.propForm.validate(valid => {

                if(valid && this.$refs[this.propForm.clientLesseeType=='0' ? 'info1':'info2'].formVerify ) {
                    this.uploadFileList.length > 0 ? this.$refs.loadFiles.submit(this.modelType, this.propForm.clientLesseeId) : this.submitForm()
                }
            })
        },
        submit(){
            if(this.propForm.clientLesseeType=='0'){
                this.$refs.info1.check()
            }else if(this.propForm.clientLesseeType!='0'){
                this.$refs.info2.check()
            }
        },
        submitForm(val){
            this.propForm.areaCode=this.propForm.provinceCode+this.propForm.cityCode+this.countryCode;
          /*  if( this.propForm.addressInfo){
                this.propForm.address = this.chArea + this.propForm.addressInfo
            }else {
                this.propForm.address = this.chArea
            }*/

            for(var i=0;i<this.editPersons.length;i++){
                this.editPersons[i].clientLesseeId=val
            }
            this.$refs.propForm.validate(valid => {
                if(valid){
                    if(this.propForm.clientLesseeId){
                        for(let i=0;i<this.editPersons.length;i++){
                            this.editPersons[i].clientLesseeId=this.propForm.clientLesseeId
                        }
                        putObj(Object.assign({},this.propForm,{clientLesseeLinkinfos:this.editPersons},{delClientLesseeLinkinfos:this.delPersons})).then(rep => {
                            if(rep.data.code === 0){
                                this.$store.commit("delHistoryRoute", this.$route.fullPath);
                                this.$router.push("/client-manage/lessee-manage")
                            }else {
                                this.$message.error("修改失败");
                            }
                        })
                    }else {
                        this.propForm.clientLesseeId = val
                        for(let i=0;i<this.editPersons.length;i++){
                            this.editPersons[i].clientLesseeId=this.propForm.clientLesseeId
                        }
                        addObj(Object.assign({},this.propForm,{clientLesseeLinkinfos:this.editPersons})).then(rep => {
                            if(rep.data.code === 0){
                                this.$store.commit("delHistoryRoute", this.$route.fullPath);
                                this.$router.push("/client-manage/lessee-manage")

                            }else {
                                this.$message.error("新增失败");
                            }
                        }).catch((e)=> {
                            console.log(e)
                        })
                    }

                }
            })
        },
        beforeUpload() {
            // this.loadAction('请稍等...')
        },
        onSuccess(response, file, fileList) {
            if (response.data) {
                this.submitForm(response.data)
                this.$refs.loadFiles.getFiles(response.data);
            } else {
                this.err('提交失败')
            }
        },
        onError(err, file, fileList) {
            this.err('提交失败')
        },
        lesseeDataFilter(val) {
            this.formData.clientLesseeType = val;
            if (val) { //val存在
                this.lesseeOptions = this.lesseeOptionsCopy.filter((item) => {
                    if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
                        return true
                    }
                })
            } else { //val为空时，还原数组
                this.lesseeOptions = this.lesseeOptionsCopy;
            }
        },
        certificateDataFilter(val) {
            this.formData.certificateType = val;
            if (val) { //val存在
                this.certificateOptions = this.certificateOptionsCopy.filter((item) => {
                    if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
                        return true
                    }
                })
            } else { //val为空时，还原数组
                this.certificateOptions = this.certificateOptionsCopy;
            }
        },
    },
};
